package network;

import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 苏西西
 * Date: 2023-10-20
 * Time: 9:40
 */
public class TcpEchoClient {
    //当前这里的socket既给服务器用，又给客户端用，
    private Socket socket = null;
    public TcpEchoClient(String serverIp,int serverPort) throws IOException {
        //Socket构造方法能够识别点分十进制格式的ip地址，比DatagramPacket更方便
        //new这个对象的同时，就会进行Tcp连接操作
        socket = new Socket(serverIp,serverPort);
    }
    public void start(){
        System.out.println("客户端启动！");
        Scanner scanner = new Scanner(System.in);

        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
            while (true){
                //1.先从键盘上读取用户输入的内容
                System.out.print(" >");
                String request  = scanner.next();
                if(request.equals("exit")){
                    System.out.println("goodbye");
                    break;
                }
                //2.把读到的内容构造成请求，发送给服务器
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(request);
                //此处加上flush，保证我们的数据确实发送出去了
                printWriter.flush();
                //3.读取服务器的响应，
                Scanner respScanner = new Scanner(inputStream);
                String response = respScanner.next();

                //4.把响应的内容给显示到界面上
                System.out.println(response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client = new TcpEchoClient("127.0.0.1",1111);
        client.start();
    }
}
